import os

def load_mapping(file_path: str):
    """
    Loads an encoding mapping from the provided BASIC.txt mapping file.

    The mapping block is enclosed between <NEW> and </NEW> tags.
    Each non-empty line in the block should have the format:
        <character><code>
    For example:
        A38

    A decoding mapping is also created by swapping keys and values.

    Returns:
        A tuple (encoding_mapping, decoding_mapping)
    """
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"Mapping file '{file_path}' not found.")
    with open(file_path, encoding='utf-8') as f:
        content = f.read()
    start = content.find("<NEW>")
    end = content.find("</NEW>")
    if start == -1 or end == -1:
        raise ValueError("Mapping block not found in file.")
    mapping_block = content[start+len("<NEW>"):end]
    mapping = {}
    for line in mapping_block.splitlines():
        line = line.strip()
        if line:
            key = line[0]
            code = line[1:].strip()
            mapping[key] = code
    decoding = {v: k for k, v in mapping.items()}
    return mapping, decoding

def encode_text(text: str, encoding_map: dict) -> str:
    """
    Encodes the text by replacing each character with its code from the mapping.
    Characters not found in the map remain unchanged.
    Spaces are removed from the output.
    """
    result = []
    for ch in text:
        if ch == " ":
            continue
        result.append(encoding_map.get(ch, ch))
    return ''.join(result)

def decode_text(text: str, decoding_map: dict) -> str:
    """
    Decodes the text by matching two-character codes from the decoding map.
    If a two-character match is found, it is replaced with the corresponding character.
    Otherwise, the character is kept as is.
    """
    result = []
    i = 0
    while i < len(text):
        if i + 2 <= len(text) and text[i:i+2] in decoding_map:
            result.append(decoding_map[text[i:i+2]])
            i += 2
        else:
            result.append(text[i])
            i += 1
    return ''.join(result)

def main(text,type):
    # Load BASIC.txt mapping for encoding/decoding
    mapping_file = r"f:\cinux\disk\bcode\BASIC.txt"
    try:
        enc_map, dec_map = load_mapping(mapping_file)
    except Exception as e:
        print("Error loading mapping:", e)
        exit(1)
    
    # Test text for encoding and decoding
    original_text =text
    encoded = encode_text(original_text, enc_map)
    decoded = decode_text(encoded, dec_map)
    if type=="e":
        return encoded
    elif type=="d":
        return decoded
    else:
        return "type error"
    #print(original_text,encoded, decoded)
    '''
    print("Original:", original_text)
    print("Encoded:",)
    '''